# -*- coding: utf-8 -*-
import json
import os

current_path = os.path.dirname(__file__)
root_path = os.path.split(current_path)


def error(message=''):
    resp = dict()
    resp['status'] = 'error'
    resp['message'] = message
    return json.dumps(resp).encode().decode('unicode_escape')


def success(message='', **kwargs):
    resp = dict()
    resp['status'] = 'success'
    resp['message'] = message
    for key, parameter in kwargs.items():
        resp[key] = parameter
    return json.dumps(resp).encode().decode('unicode_escape')


def get_parameters(request, *args):
    def check_parameters(param, args_1):
        try:
            for val in args_1:
                if (param is None) or (val not in param):
                    return False
                if len(param[val]) == 0:
                    return False
        except:
            pass
        return True

    http_method = request.method
    if http_method == 'POST':
        datas = request.get_data()
        if not datas:  # 检测是否有数据
            return False, error('缺少参数')
        datas = json.loads(datas.decode('utf-8').replace("'", "\""))
        if not check_parameters(datas, args):
            return False, error('缺少必填参数:%s' % args)
        return True, [datas[x] for x in args]
    else:
        for param in args:
            if not request.values.get(param):  # 检测是否有数据
                return False, error('缺少必填参数:%s' % param)
        return True, [request.values.getlist(x) for x in args]


def is_json(text):
    try:
        json.loads(text)
    except ValueError:
        return False
    return True


def find_last(string, chars):
    last_pos = -1
    while True:
        pos = string.find(chars, last_pos + 1)
        if pos == -1:
            return last_pos
        last_pos = pos


def type_transform_boolean(param):
    """
    boolean类型转换
    :param param:
    :return:
    """
    if param in ['true', 'True', '是']:
        return True
    if param in ['false', 'False', '否']:
        return False
    return param

#
# if __name__ == '__main__':
#     import time
#     print(time_to_str(round(time.time())))
